package filter;

import Utils.BaseMessage;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 禁止未登录查看
 */
@WebFilter(filterName = "isLoginFilter", urlPatterns = {
        "/api/User/isLogin/*",
        "/api/CreditCard/isLogin/*",
})
public class isLoginFilter implements Filter {
    private Logger logger = Logger.getLogger(isLoginFilter.class);

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        logger.info("isLoginFilter加载成功");
        if (session.getAttribute("userMsg") == null) {
            response.getWriter().print(JSON.toJSONString(new BaseMessage(1, "您暂未登录,请登录后操作", null)));
            return;
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
